package com.jumi.microservice.controller.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.annon.IgnoreUrlsAnnon;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jm.member.common.messages.entity.WechatAppletResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.dto.reponse.api.LoginResponse;
import com.jumi.microservice.entity.JmUser;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/appletLogin")
@Api(tags = "C-小程序登录接口")
public class AppletLoginController extends LoginController{

    @IgnoreUrlsAnnon("/wechatApplet")
    @GetMapping("/wechatApplet")
    @ApiOperation("微信小程序获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inviterId",value = "邀请人id"),
            @ApiImplicitParam(name = "registerId",value = "registerId")
    })
    public ResponseResult wechatApplet(@ApiParam(required = true, value = "code") @RequestParam String code,
                                       Long inviterId, String registerId) {
//        weChartService.setWeChartConfigAppid("wxd0cb7df61db801f7");
        weChartService.setWeChartConfigAppid("2123213213213");
        weChartService.setWeChartConfigAppSecret("3b5652fbba087447505ee2978fc2e728");
        WechatAppletResponse weAppletUserInfo = weChartService.getWeAppletUserInfo(code);
        logger.info("微信小程序session_key:" + weAppletUserInfo.getSession_key());
        logger.info("微信小程序unionid:" + weAppletUserInfo.getUnionid());
        logger.info("微信小程序openid:" + weAppletUserInfo.getOpenid());
        String openid = weAppletUserInfo.getOpenid();
        if (StrUtil.isNotEmpty(openid)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("wx_openid", openid);
            JmUser user = userService.getOne(wrapper);
            if (ObjectUtil.isEmpty(user)) {
                return ResponseResult.error(500,"用户未绑定", weAppletUserInfo);
            }
            Map map = new HashMap();
            LoginResponse response = login(user,inviterId,registerId);
            map.put("userInfo", user);
            map.put("response", response);
            return ResponseResult.success("登录成功", map);
        }
        return ResponseResult.error(500,"微信获取失败", weAppletUserInfo);
    }

    @IgnoreUrlsAnnon("/wechatLogin")
    @GetMapping("/wechatLogin")
    @ApiOperation("微信小程序用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inviterId",value = "邀请人id"),
            @ApiImplicitParam(name = "registerId",value = "registerId")
    })
    public ResponseResult wechatLogin(@RequestParam(required = true, value = "iv") String iv, @RequestParam(required = true, value = "encryptedData") String encryptedData, @RequestParam(required = true, value = "sessionKey") String sessionKey,
                                      @RequestParam(required = true, value = "openId") String openId, @RequestParam(value = "avatar") String avatar, @RequestParam(value = "unionid") String unionid, @RequestParam(required = false, value = "nickName") String nickName,
                                      String inviterId, String registerId) {
        Long memberInviterId =  (inviterId != null && inviterId.length() != 0) ?  Long.parseLong(inviterId) : 0;
        Object phoneInfo = getPhoneNumber(encryptedData, sessionKey, iv);
        if (ObjectUtil.isEmpty(phoneInfo)) {
            return ResponseResult.error("参数错误");
        }
        String phone = (String) ((JSONObject) phoneInfo).get("phoneNumber");
        JmUser userByMobile = userService.getUserByMobile(phone);
        Map map = new HashMap();
        if (ObjectUtil.isNotEmpty(userByMobile)) {
            String client = ServletUtils.getStrHeader(JwtAdminInfo.loginClient);//登录的客户端
            String model = ServletUtils.getStrHeader(JwtAdminInfo.loginModel);//登录时的手机型号
            deleteOpenId(openId);
            userByMobile.setWxOpenid(openId);
            userByMobile.setWeixinUnionid(unionid);
            map.put("userInfo", userByMobile);
            map.put("response", doLogin(userByMobile,client,model,registerId));
            return ResponseResult.success("登录成功", map);
        }
        JmUser newUser = new JmUser();
        if (ObjectUtil.isNotNull(nickName)) {
            newUser.setName(nickName);
        }
        newUser.setMobile(phone);
        newUser.setWxOpenid(openId);
        newUser.setWeixinUnionid(unionid);
        newUser.setAvatar(avatar);
        LoginResponse response = login(newUser,memberInviterId,registerId);
        map.put("userInfo", newUser);
        map.put("response", response);
        return ResponseResult.success("登录成功", map);
    }
}
